import 'package:decimal/decimal.dart';
import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import '../../resources/kq_pad_theme_colors.dart';
import 'base/kq_pad_chart_line_bae_mode.dart';
import 'base/kq_pad_chart_model.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';
import 'package:intl/intl.dart' as inl;

class KqPdaChartLineModel {
  ///通用图标布局
  KqPadChartModel chartModel;

  ///输入数据集合
  List<List<KqPdaChartLineValue>> chartArray;

  ///以右纵轴为竖轴的布局
  List<List<KqPdaChartLineValue>>? chartRightArray;

  ///
  List<KqPdaDividerValue>? yDividerList;

  ///
  List<KqPdaDividerValue>? xDividerList;

  KqPadChartLineBaseModel baseModel;

  KqPdaChartLineModel({
    required this.chartModel,
    this.chartArray = const [],
    this.chartRightArray,
    required this.baseModel,
    this.yDividerList,
    this.xDividerList,
  });

  void _initData() {
    chartModel.initData();
    chartModel.xColor = chartModel.xColor ?? KqPadThemeColors.text59;
    chartModel.yColor = chartModel.yColor ?? KqPadThemeColors.text59;
    chartModel.axisColor = chartModel.axisColor ?? KqPadThemeColors.bgEB;
    chartModel.dividerColor = chartModel.dividerColor ?? KqPadThemeColors.bgEB;
    baseModel.maxCross = 0;
    baseModel.maxHeight = 0;
    baseModel.crossShowList = [];
    baseModel.avgYPointList = [];
    baseModel.yHeight = chartModel.sizeHeight -
        chartModel.yTop! -
        chartModel.yBottom! -
        chartModel.yAxisTop!;
  }

  ///设置内容
  void setValueList(
      List<List<KqPdaChartLineValue>> list, KqPadChartModel chartModelValue,
      {List<List<KqPdaChartLineValue>>? rightList}) {
    chartModel = chartModelValue;
    chartArray = list;
    chartRightArray = rightList;
    _initData();
    int index = 0;
    for (var i = 0; i < list.length; i++) {
      List<KqPdaChartLineValue> e = list[i];
      index = baseModel.maxCross > e.length ? index : i;
      baseModel.maxCross =
          baseModel.maxCross > e.length ? baseModel.maxCross : e.length;
    }
    baseModel.xValue = [];
    if (list.length > index) {
      List<KqPdaChartLineValue> maxLine = list[index];
      maxLine.map((e) => baseModel.xValue.add(e.xValue)).toList();
    }
    if (chartModel.leftYAxisList.isNotNullOrEmpty &&
        chartModel.rightYAxisList.isNotNullOrEmpty) {
      setTwoYAxisInfo();
      getAbscissaList();
      getLeftOrRightOrdinateList();
      chartArray.map((e) {
        setXPointToValueList(e);
        setYPointToValueList(e, firsPointY: chartModel.leftYAxisList!.first);
      }).toList();
      chartRightArray?.map((e) {
        setXPointToValueList(e);
        setYPointToRightValueList(e,
            firsPointY: chartModel.rightYAxisList!.first);
      }).toList();
    } else {
      setUsuallyInfo();
      getAbscissaList();
      getOrdinateList();
      if (chartModel.avgValues!.isNotEmpty) {
        for (var i = 0; i < chartModel.avgValues!.length; i++) {
          double avgYPoint = double.parse(chartModel.avgValues![i]);
          baseModel.avgYPointList.add(
              ((baseModel.maxHeight - avgYPoint) / baseModel.maxHeight) *
                      baseModel.yHeight +
                  chartModel.yTop! +
                  chartModel.yAxisTop!);
        }
        chartArray.map((e) {
          setXPointToValueList(e);
          setYPointToValueList(e);
        }).toList();
      } else {
        chartArray.map((e) {
          setXPointToValueList(e);
          setYPointToValueList(e);
          getAvgValuePointList(e);
        }).toList();
      }
    }
    setCustomDividerInfo();
  }

  ///设置自定义分割线布局内容
  setCustomDividerInfo() {
    if (xDividerList.isNotNullOrEmpty) {
      double maxWidth = baseModel.xList.last - baseModel.xList.first;
      for (var i = 0; i < xDividerList!.length; i++) {
        KqPdaDividerValue info = xDividerList![i];
        info.valueDouble = maxWidth * info.value + baseModel.xList.first;
      }
    }
    if (yDividerList.isNotNullOrEmpty) {
      for (var i = 0; i < yDividerList!.length; i++) {
        double height = baseModel.yList.last - baseModel.yList.first;
        KqPdaDividerValue info = yDividerList![i];
        info.valueDouble = height * (1 - info.value) + baseModel.yList.first;
      }
    }
  }

  //设置左右2条Y轴时候内容
  setTwoYAxisInfo() {
    baseModel.maxHeight =
        chartModel.leftYAxisList!.last - chartModel.leftYAxisList!.first;
    baseModel.maxRightHeight =
        chartModel.rightYAxisList!.last - chartModel.rightYAxisList!.first;
    var maxYLeftText = TextPainter(
        textAlign: TextAlign.right,
        ellipsis: '.',
        maxLines: 1,
        text: TextSpan(
            text: chartModel.leftYAxisList!.last.toString(),
            style: TextStyle(fontSize: chartModel.yFont)),
        textDirection: TextDirection.ltr)
      ..layout();
    chartModel.xLeft = maxYLeftText.size.width + chartModel.yFont!;
    var maxYRightText = TextPainter(
        textAlign: TextAlign.left,
        ellipsis: '.',
        maxLines: 1,
        text: TextSpan(
            text: chartModel.rightYAxisList!.last.toString(),
            style: TextStyle(fontSize: chartModel.yFont)),
        textDirection: TextDirection.ltr)
      ..layout();
    chartModel.endPointXWidth = maxYRightText.size.width + chartModel.yFont!;
    baseModel.xWidth = chartModel.sizeWidth -
        chartModel.xLeft! -
        chartModel.xRight! -
        chartModel.endPointXWidth;
  }

  ///正常只有左边Y轴时候计算布局范围以及设置最大值
  setUsuallyInfo() {
    if (!chartModel.isFixMaxY) {
      chartArray.map((List<KqPdaChartLineValue> e) {
        e.map((KqPdaChartLineValue value) {
          double y = double.parse(value.yValue);
          if (chartModel.maxY > y) {
            baseModel.maxHeight = baseModel.maxHeight > chartModel.maxY
                ? baseModel.maxHeight
                : chartModel.maxY;
          } else {
            baseModel.maxHeight =
                baseModel.maxHeight > y ? baseModel.maxHeight : y;
          }
        }).toList();
      }).toList();
    } else {
      baseModel.maxHeight = chartModel.maxY;
    }
    var maxYText = TextPainter(
        textAlign: TextAlign.right,
        ellipsis: '.',
        maxLines: 1,
        text: TextSpan(
            text: baseModel.maxHeight.toString(),
            style: TextStyle(fontSize: chartModel.yFont)),
        textDirection: TextDirection.ltr)
      ..layout();
    chartModel.xLeft = chartModel.xLeft == 40.dm
        ? maxYText.size.width + chartModel.yFont!
        : chartModel.xLeft;
    baseModel.xWidth =
        chartModel.sizeWidth - chartModel.xLeft! - chartModel.xRight!;
  }

  ///获取横坐标数组
  void getAbscissaList() {
    if (baseModel.maxCross < 2) {
      baseModel.crossSpacing = baseModel.xWidth - chartModel.initialPointX;
    } else {
      baseModel.crossSpacing = (baseModel.xWidth - chartModel.initialPointX) /
          (baseModel.maxCross - 1);
    }
    baseModel.xList = [];
    for (int i = 0;
        i < (baseModel.maxCross < 2 ? 2 : baseModel.maxCross);
        i++) {
      double absPoint = baseModel.crossSpacing * i +
          chartModel.xLeft! +
          chartModel.initialPointX;
      baseModel.xList.add(absPoint);
    }
  }

  ///获取左右的纵坐标数组
  void getLeftOrRightOrdinateList() {
    double rowSpacing =
        baseModel.yHeight / (chartModel.leftYAxisList!.length - 1);
    baseModel.yList = [];
    baseModel.yValue = [];
    baseModel.yRightValue = [];
    for (int i = 0; i < chartModel.leftYAxisList!.length; i++) {
      double value =
          chartModel.leftYAxisList![chartModel.leftYAxisList!.length - i - 1];
      baseModel.yValue.add(inl.NumberFormat("#0.##").format(value));
      baseModel.yList
          .add(rowSpacing * i + chartModel.yTop! + chartModel.yAxisTop!);
    }
    for (int i = 0; i < chartModel.rightYAxisList!.length; i++) {
      double value =
          chartModel.rightYAxisList![chartModel.rightYAxisList!.length - i - 1];
      baseModel.yRightValue.add(inl.NumberFormat("#0.##").format(value));
    }
  }

  ///获取纵坐标数组
  void getOrdinateList() {
    double rowSpacing = baseModel.yHeight / (chartModel.rowCount - 1);
    double ySpac = baseModel.maxHeight / (chartModel.rowCount - 1);
    baseModel.yList = [];
    baseModel.yValue = [];
    for (int i = 0; i < chartModel.rowCount; i++) {
      baseModel.yList
          .add(rowSpacing * i + chartModel.yTop! + chartModel.yAxisTop!);
      if (i == 0) {
        int maxYvalue = (baseModel.maxHeight * 10).ceil();
        String value = (maxYvalue / 10).toString();
        baseModel.yValue.add(Decimal.parse(value).toString());
      } else {
        double yDouble = ySpac * (chartModel.rowCount - i - 1);
        String value = (yDouble.toStringAsFixed(1)).toString();
        baseModel.yValue.add(Decimal.parse(value).toString());
      }
    }
  }

  ///获取平均线数组
  void getAvgValuePointList(List<KqPdaChartLineValue> valueList) {
    if (valueList.isNotEmpty) {
      double sum = valueList.fold(
          0,
          (double preValue, KqPdaChartLineValue data) =>
              preValue + double.parse(data.yValue));
      double avgYPoint = sum / valueList.length;
      String value = (avgYPoint.toStringAsFixed(2)).toString();
      chartModel.avgValues!.add(Decimal.parse(value).toString());
      baseModel.avgYPointList.add(
          ((baseModel.maxHeight - avgYPoint) / baseModel.maxHeight) *
                  baseModel.yHeight +
              chartModel.yTop! +
              chartModel.yAxisTop!);
    }
  }

  ///给内容数组赋值横坐标值
  void setXPointToValueList(List<KqPdaChartLineValue> valueList) {
    if (valueList.length > 1) {
      for (int i = 0; i < valueList.length; i++) {
        KqPdaChartLineValue value = valueList[i];
        value.xPoint = baseModel.xList[i];
      }
      if (chartModel.crossCount != 0 &&
          (chartModel.crossShowList.isNullOrEmpty)) {
        baseModel.crossShowList = [];
        double interval = baseModel.maxCross / (chartModel.crossCount - 1);
        for (int i = 0; i < chartModel.crossCount; i++) {
          if (i == 0) {
            baseModel.crossShowList.add(0);
          } else if (i == chartModel.crossCount - 1) {
            baseModel.crossShowList.add(baseModel.maxCross - 1);
          } else if (i < baseModel.maxCross) {
            baseModel.crossShowList.add((interval * i).truncate());
          }
        }
      } else {
        baseModel.crossShowList = chartModel.crossShowList ?? [];
      }
    } else {
      if (valueList.isNotEmpty) {
        KqPdaChartLineValue value = valueList.first;
        value.xPoint = baseModel.xList.first + baseModel.xWidth / 2;
      }
    }
  }

  ///给内容数组赋值纵坐标值
  void setYPointToValueList(List<KqPdaChartLineValue> valueList,
      {double firsPointY = 0}) {
    for (int i = 0; i < valueList.length; i++) {
      KqPdaChartLineValue value = valueList[i];
      double yHValue = double.tryParse(value.yValue) ?? 0;
      value.yPoint =
          ((baseModel.maxHeight - yHValue + firsPointY) / baseModel.maxHeight) *
                  baseModel.yHeight +
              chartModel.yTop! +
              chartModel.yAxisTop!;
    }
  }

  ///给右内容数组赋值纵坐标值
  void setYPointToRightValueList(List<KqPdaChartLineValue> valueList,
      {double firsPointY = 0}) {
    for (int i = 0; i < valueList.length; i++) {
      KqPdaChartLineValue value = valueList[i];
      double yHValue = double.tryParse(value.yValue) ?? 0;
      value.yPoint = ((baseModel.maxRightHeight - yHValue + firsPointY) /
                  baseModel.maxRightHeight) *
              baseModel.yHeight +
          chartModel.yTop! +
          chartModel.yAxisTop!;
    }
  }
}

class KqPdaDividerValue {
  ///百分比
  double value;

  ///分割线颜色
  Color dividerColor;

  ///线的宽度,默认1
  double lineWidth;

  ///是否为虚线，默认true
  bool isDottedLine;

  ///真实的x或者y点位置
  double valueDouble = 0;

  ///是否是虚线
  KqPdaDividerValue({
    required this.value,
    required this.dividerColor,
    this.lineWidth = 1,
    this.isDottedLine = true,
  });
}

class KqPdaChartLineValue {
  String xValue;
  String yValue;

  ///文案样式
  TextStyle style;

  ///当点击或者滑动到该区域时是否显示文案，只针对isShowValue=false且isShowClickValue或isShowSlideValue为True才会被使用
  bool isShow;

  ///是否显示内容点的分割线
  bool isCountDivider;

  ///内容分割线的颜色
  Color dividerColor;

  ///分割线是否为实线，默认为false
  bool dividerLineSolid;

  ///线的宽度,默认1
  double? lineWidth;

  ///点的颜色
  Color? pointColor;

  ///点的大小
  double? pointWidth;

  Color? lineColor;

  ///以下为自动计算，无需传入
  double xPoint = 0;
  double yPoint = 0;
  KqPdaChartLineValue({
    required this.xValue,
    required this.yValue,
    this.style = const TextStyle(fontSize: 12, color: KqPadThemeColors.text59),
    this.isCountDivider = false,
    this.dividerLineSolid = false,
    this.dividerColor = KqPadThemeColors.textLightBlue,
    this.pointColor,
    this.lineColor,
    this.isShow = false,
    this.lineWidth,
    this.pointWidth,
  });
}
